//testItemKernel.c

#include "kernel.h"
#include "kernel_hwdep.h"

#define TEST_PATTERN_1 0xAA
#define TEST_PATTERN_2 0x55

mailbox *mb;

int nTest1=0, nTest2=0, nTest3=0;
int dummy=0;
unsigned int current_highest_deadline = 100;


void task1(void)
{
       static int nData_t1 = TEST_PATTERN_1;
       set_deadline(current_highest_deadline++); /* switch to other task */
       dummy=no_messages(mb);
       if(  abs(dummy) != 1 ) terminate(); /* ERROR */;

       if(send_wait(mb,&nData_t1) == DEADLINE_REACHED) /* -> t2 */
               terminate(); /* ERROR */

       /* start test 2 */
       nData_t1 = TEST_PATTERN_2;
       if(send_wait(mb,&nData_t1) == DEADLINE_REACHED) /* -> t2 */
               terminate(); /* ERROR */

       set_deadline(current_highest_deadline++); /* switch to other task */

/* No easy way to test DEADLINE_REACHED without using the timer */
/* start test 3 */
//      if(send_wait(mb,&nData_t1) == DEADLINE_REACHED) {
//              if( no_messages(mb) != 0 )
//                      terminate(); /* ERROR */;
       nTest3 = 1;

       if (nTest1*nTest2*nTest3) /* test completed */
       /* Test ok! */
        terminate(); /* PASS, no receiver */
//      } else {
        terminate(); /* ERROR */
//      }
}

void task2(void)
{
      static int nData_t2;
      nData_t2 = 0;
       if(receive_wait(mb,&nData_t2) == DEADLINE_REACHED) /* -> t1 */
               terminate(); /* ERROR */

       if( no_messages(mb) != 0 ) terminate(); /* ERROR */;

       if (nData_t2 == TEST_PATTERN_1) nTest1 = 1;

       set_deadline(current_highest_deadline++); /* switch to other task */

       /* start test 2 */

       if( abs(no_messages(mb)) != 1 ) terminate(); /* ERROR */;

       if(receive_wait(mb,&nData_t2) == DEADLINE_REACHED) /* -> t1 */
               terminate(); /* ERROR */

       dummy=no_messages(mb);

       if( dummy != 0 ) terminate(); /* ERROR */;

       if (nData_t2 == TEST_PATTERN_2) nTest2 = 1;


       /* Start test 3 */
       terminate();
}

void main(void)
{
  if (init_kernel() != OK ) {
/* Memory allocation problems */
while(1);
  }

  if (create_task( task1, current_highest_deadline ) != OK ) {
/* Memory allocation problems */
       while(1);
  }

  if (create_task( task2, current_highest_deadline++ ) != OK ) {
       /* Memory allocation problems */
       while(1);
  }

  if ( ( mb=create_mailbox(1,sizeof(int)) ) == NULL) {
       /* Memory allocation problems */
       while(1);
  }

  run(); /* First in readylist is task1 */
}

//void Idle (void)
//{
//while(1);
//}